package down2;

import javax.servlet.ServletOutputStream;

import up6.store.FileBlockReader;

import java.io.IOException;
import java.io.OutputStream;

public class WebWriter {
    public int cacheSize = 1048576;//1MB，默认内存块大小

    /// <summary>
    ///
    /// </summary>
    /// <param name="fr"></param>
    /// <param name="hr"></param>
    /// <param name="pathSvr"></param>
    /// <param name="blockSize">需要下载的大小</param>
    public void write(FileBlockReader fr, ServletOutputStream os, String pathSvr, long offset, int blockSize)
    {   	
        // 总共需要下载的长度
        int dataToRead = blockSize;
        //每次读1MB，然后传给终端
        int buf_size = Math.min(this.cacheSize, blockSize);
        byte[] buffer = null;
        int length=0;

        try {
            while (dataToRead > 0)
            {
                buffer = fr.read(pathSvr, offset, buf_size);
                length = buffer.length;
                dataToRead -= length;
                offset += length;//
                buf_size = dataToRead < buf_size ? dataToRead : buf_size;

                os.write(buffer, 0, length);
                os.flush();
            }
            os.close();
            os=null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
